/* eslint-disable */
export const string = {
	//去除空格  type 1-所有空格  2-前后空格  3-前空格 4-后空格
	trim(str,type){
	    switch (type){
	        case 1:return str.replace(/\s+/g,"");
	        case 2:return str.replace(/(^\s*)|(\s*$)/g, "");
	        case 3:return str.replace(/(^\s*)/g, "");
	        case 4:return str.replace(/(\s*$)/g, "");
	        default:return str;
	    }
	},

	//字符串检测 checkType('165226226326','phone') false
	checkType(str, type) {
	    switch (type) {
	        case 'email':
	            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
	        case 'phone':
	            return /^1[3|4|5|7|8][0-9]{9}$/.test(str);
	        case 'tel':
	            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
	        case 'number':
	            return /^[0-9]$/.test(str);
	        case 'english':
	            return /^[a-zA-Z]+$/.test(str);
	        case 'chinese':
	            return /^[\u4E00-\u9FA5]+$/.test(str);
	        case 'lower':
	            return /^[a-z]+$/.test(str);
	        case 'upper':
	            return /^[A-Z]+$/.test(str);
	        default :
	            return true;
	    }
	},

	//字符串替换(字符串,要替换的字符,替换成什么)
	replaceAll(str,AFindText,ARepText){
	　　　var raRegExp = new RegExp(AFindText,"g");
	　　　return str.replace(raRegExp,ARepText);
	},

	//replaceStr(字符串,字符格式, 替换方式,替换的字符（默认*）)
	replaceStr(str, regArr, type, ARepText) {
	    var regtext = '', Reg = null,replaceText = ARepText || '*';
		function times(str, num){
			return num > 1 ? str += times(str, --num): str;
		}
	    //replaceStr('18819322663',[3,5,3],0)
	    //188*****663
	    //repeatStr是在上面定义过的（字符串循环复制），大家注意哦
	    if (regArr.length === 3 && type === 0) {
	        regtext = '(\\w{' + regArr[0] + '})\\w{' + regArr[1] + '}(\\w{' + regArr[2] + '})'
	        Reg = new RegExp(regtext);
	        var replaceCount = times(replaceText, regArr[1]);
	        return str.replace(Reg, '$1' + replaceCount + '$2')
	    }
	    //replaceStr('asdasdasdaa',[3,5,3],1)
	    //***asdas***
	    else if (regArr.length === 3 && type === 1) {
	        regtext = '\\w{' + regArr[0] + '}(\\w{' + regArr[1] + '})\\w{' + regArr[2] + '}'
	        Reg = new RegExp(regtext);
	        var replaceCount1 = times(replaceText, regArr[0]);
	        var replaceCount2 = times(replaceText, regArr[2]);
	        return str.replace(Reg, replaceCount1 + '$1' + replaceCount2)
	    }
	    //replaceStr('1asd88465asdwqe3',[5],0)
	    //*****8465asdwqe3
	    else if (regArr.length === 1 && type == 0) {
	        regtext = '(^\\w{' + regArr[0] +  '})'
	        Reg = new RegExp(regtext);
	        var replaceCount = times(replaceText, regArr[0]);
	        return str.replace(Reg, replaceCount)
	    }
	    //replaceStr('1asd88465asdwqe3',[5],1,'+')
	    //"1asd88465as+++++"
	    else if (regArr.length === 1 && type == 1) {
	        regtext = '(\\w{' + regArr[0] +  '}$)'
	        Reg = new RegExp(regtext);
	        var replaceCount = times(replaceText, regArr[0]);
	        return str.replace(Reg, replaceCount)
	    }
	}
}


export const array = {
  //生成多个数组
  moreNewArray(arr,num){
    let arrList = [];
    let newArr = [];
    let numList = [];
    let n = 0;
    if(list.length > num){
        list.forEach((item,index)=>{
            if( index % num === 0 ){
                numList.push(index);
            }
        })
        numList.forEach((item,index)=>{
            newArr[n++] = list.slice(item, item+num);
            arrList = newArr;
        })
    }
    return arrList
  },

  //数组排序
  arraySort(arr, sortText) {
    if (!sortText) {
        return arr
    }
    var _sortText = sortText.split(',').reverse(), _arr = arr.slice(0);
    for (var i = 0, len = _sortText.length; i < len; i++) {
        _arr.sort(function (n1, n2) {
            return n1[_sortText[i]] - n2[_sortText[i]]
        })
    }
    return _arr;
  },

  //数组去除空对象
  arrclearNotObj(arr){
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] == null || arr[i] == "" || JSON.stringify(arr[i]) == "{}") {
        arr.splice(i, 1);
        i = i - 1;
      }
    }
    return arr
  },

	//数组去重(id)
	removeRepeatArrayId(arr,id) {
		let result = [];
		let obj = {};
		if(!id){
			id = 'id'
		}
		for(let i =0; i<arr.length; i++){
			let objId = arr[i][id]
			if(!obj[objId]){
				result.push(arr[i]);
				obj[objId] = true;
			}
		}
		return result;
	},

  //数组去重(全相等)
  removeRepeatArray(list){
    let type = Number;
    list.forEach(item => {
      if( Object.prototype.toString.call(item) === '[object Object]'){
        type = 1;
      }else{
        type = 0;
      }
    });
    if(type == 1){
     let uniques = [];
     let stringify = {};
     for (let i = 0; i < list.length; i++) {
         let keys = Object.keys(list[i]);
         keys.sort(function(a, b) {
             return (Number(a) - Number(b));
         });
         let str = '';
         for (let j = 0; j < keys.length; j++) {
             str += JSON.stringify(keys[j]);
             str += JSON.stringify(list[i][keys[j]]);
         }
         if (!stringify.hasOwnProperty(str)) {
             uniques.push(list[i]);
             stringify[str] = true;
         }
      }
     uniques = uniques;
     return uniques;
    }else{
      return Array.from(new Set(list))
    }
  },

	//数组交集
	arrRepetitionExtract(arr){
    const mapper = {};
    const newArr = [];
    for (let item of arr) {
      const { id } = item;
      if (mapper[id]) {
        newArr.push(item)
      } else {
        mapper[id] = true
      }
    }
    return newArr;
	},

  //比较相等并删除
  compareEqualDel(arr1,arr2){
    let list = arr2.filter(items => {
      if (!arr1.includes(items)) return items;
    })
    return list
  }

}

//数据参数
export const url = {
  setUrlPrmt(obj) {
    let _rs = [];
    for (let p in obj) {
        if (obj[p] != null && obj[p] != '') {
            _rs.push(p + '=' + obj[p])
        };
    };
    return _rs.join('&');
  }
}

// 获取当天时间
export const time = {
  getNow(type){
    let now = new Date()
    let year = now.getFullYear()
    let month = now.getMonth()
    let date = now.getDate()
    let hour = now.getHours()
    let minute = now.getMinutes()
    month = month + 1
    month = month.toString().padStart(2, "0")
    date = date.toString().padStart(2, "0")
    hour = hour.toString().padStart(2, "0")
    minute = minute.toString().padStart(2, "0")
    let value = now
    switch(type){
      case 0:
        value = `${year}-${month}-${date}`
        break
      case 1:
        value = `${year}-${month}-${date}`+ ' ' +`${hour}:${minute}`
        break
      case 2:
        value = `${year}-${month}-1`
        break
      default:
        value = ''
    }
    return value
  },
   /**
   * 获取上一个月
   */
  getPreMonth(date) {
    var arr = date.split('-');
    var year = arr[0]; 
    var month = arr[1]; 
    var day = arr[2]; 
    var days = new Date(year, month, 0);
    days = days.getDate();
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
  },
  //获取上一个月天数
  getPreMonthEnd(date){
    var arr = date.split('-');
    var year = arr[0]; 
    var month = arr[1]; 
    var day = arr[2]; 
    var days = new Date(year, month, 0);
    days = days.getDate(); 
    var t2 = year + '-' + month + '-' + days;
    return t2
  },
  /**
   * 获取下一个月
   */
  getNextMonth(date) {
    var arr = date.split('-');
    var year = arr[0]; 
    var month = arr[1]; 
    var day = arr[2]; 
    var days = new Date(year, month, 0);
    days = days.getDate(); 
    var year2 = year;
    var month2 = parseInt(month) + 1;
    if (month2 == 13) {
        year2 = parseInt(year2) + 1;
        month2 = 1;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
  },
  //获取下一个月天数
  getNextMonthEnd(date){
    var arr = date.split('-');
    var year = arr[0]; 
    var month = arr[1]; 
    var day = arr[2]; 
    var days = new Date(year, month, 0);
    days = days.getDate(); 
    var year2 = year;
    var month2 = parseInt(month) + 1;
    if (month2 == 13) {
        year2 = parseInt(year2) + 1;
        month2 = 1;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + days;
    return t2;
  },
  // 本周
  getCurrentWeek() {
    //获取当前时间
    const currentDate = new Date()
    //返回date是一周中的某一天
    const week = currentDate.getDay()
    //一天的毫秒数
    const millisecond = 1000 * 60 * 60 * 24
    //减去的天数
    const minusDay = week != 0 ? week - 1 : 6
    //本周 周一
    const monday = new Date(currentDate.getTime() - minusDay * millisecond)
    //本周 周日
    const sunday = new Date(monday.getTime() + 6 * millisecond)
    return [this.formatDate(monday),this.formatDate(sunday)]
  },
  //获取上一周
  getPrevWeek(date) {
    var arr = date.split('-');
    const Time = new Date(arr[0], arr[1]-1, arr[2], 0, 0, 0); 
    let weekNum = Time.getDay() 
    weekNum = weekNum == 0 ? 7 : weekNum
    let lastDate = new Date(Time.getTime() - weekNum * 24 * 60 * 60 * 1000)
    let fitstDate = new Date(
      Time.getTime() - (weekNum + 6) * 24 * 60 * 60 * 1000
    )
    let startDate = `${fitstDate.getFullYear()}-${
      fitstDate.getMonth() + 1 < 10
        ? '0' + (fitstDate.getMonth() + 1)
        : fitstDate.getMonth() + 1
    }-${
      fitstDate.getDate() < 10
        ? '0' + fitstDate.getDate()
        : fitstDate.getDate()
    }`
    let endDate = `${lastDate.getFullYear()}-${
      lastDate.getMonth() + 1 < 10
        ? '0' + (lastDate.getMonth() + 1)
        : lastDate.getMonth() + 1
    }-${
      lastDate.getDate() < 10 ? '0' + lastDate.getDate() : lastDate.getDate()
    }`
    return [startDate, endDate]
  },
  //获取下一周
  getNextvWeek(date) {
    var arr = date.split('-');
    const Time = new Date(arr[0], arr[1]-1, arr[2], 0, 0, 0); 
    let weekNum = Time.getDay()
    weekNum = weekNum == 0 ? 7 : weekNum

    let fitstDate = new Date(
      Time.getTime() + (7 - weekNum + 1) * 24 * 60 * 60 * 1000
    )
    let lastDate = new Date(
      Time.getTime() + (7 - weekNum + 7) * 24 * 60 * 60 * 1000
    )
    let startDate = `${fitstDate.getFullYear()}-${
      fitstDate.getMonth() + 1 < 10
        ? '0' + (fitstDate.getMonth() + 1)
        : fitstDate.getMonth() + 1
    }-${
      fitstDate.getDate() < 10
        ? '0' + fitstDate.getDate()
        : fitstDate.getDate()
    }`
    let endDate = `${lastDate.getFullYear()}-${
      lastDate.getMonth() + 1 < 10
        ? '0' + (lastDate.getMonth() + 1)
        : lastDate.getMonth() + 1
    }-${
      lastDate.getDate() < 10 ? '0' + lastDate.getDate() : lastDate.getDate()
    }`
    return [startDate, endDate]
  },
  //时间格式转化
  formatDate(date){ //设置时间转换格式
    var y = date.getFullYear();  //获取年
    var m = date.getMonth() + 1;  //获取月
    m = m < 10 ? '0' + m : m;  //判断月是否大于10
    var d = date.getDate();  //获取日
    d = d < 10 ? ('0' + d) : d;  //判断日期是否大10
    return y + '-' + m + '-' + d;  //返回时间格式
  }    
}


// 校验字符串
export const validString  = (rule, value, callback) => {
    if(value == null){
      return callback(new Error('不能为空'));
    }else{
      var str = value.replace(/\s+/g,"");
      if(str.length == 0){
        return callback(new Error('不能为空'));
      }
    }
    callback();
};

//element 校验数字
export const validNumber  = (rule, value, callback) => {
    if(!Number(value)){
        return callback(new Error('请输入数字'));
    }
    callback();
};

// 递归深拷贝
export function deepCopy(obj) {
	let result = Array.isArray(obj) ? [] : {};
	for (let key in obj) {
		if (obj.hasOwnProperty(key)) {
			if (typeof obj[key] === 'object' && obj[key] !== null) {
				result[key] = deepCopy(obj[key]);
			}else {
				result[key] = obj[key];
			}
		}
	}
	return result;
}

//element 校验手机号码
export const validPhone = (rule, value, callback) => {
	const reg = /^((0\d{2,3}-\d{7,8})|(1[35784]\d{9}))$/;
	if (!value) {
		callback(new Error('请输入手机号码'))
	}else if(!Number(value)){
		callback(new Error('手机号码必须为数字'))
	}else if (!reg.test(value)) {
		callback(new Error('请输入正确的手机号码'))
	} else {
		callback()
	}
}
